package com.icongyou.enterprise.talent_profile.service;

import com.icongyou.enterprise.data_aggregation.entity.*;
import com.icongyou.enterprise.data_aggregation.entity.vo.StudentTopSubmissionDetailVO;
import com.icongyou.enterprise.data_aggregation.entity.vo.StudentTopSubmissionSimpleVO;
import com.icongyou.enterprise.data_aggregation.mapper.DataAggregationMapper;
import com.icongyou.enterprise.data_aggregation.service.DataAggregationService;
import com.icongyou.enterprise.talent_profile.entity.vo.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class ProfileServiceImpl implements ProfileService {

    private final DataAggregationService dataAggregationService;
    private final DataAggregationMapper dataAggregationMapper;

    @Override
    public StudentBasicVO getStudentBasicInfo(String studentId) {

        // 获取学生基本信息
        UserEntity student = dataAggregationService.getStudentById(studentId);
        if (student == null) {
            throw new RuntimeException("学生不存在");
        }

        // 获取学校信息（通过租户表）
        TenantEntity tenant = dataAggregationService.getTenantById(student.getTenantId());

        StudentBasicVO basicVO = new StudentBasicVO();
        BeanUtils.copyProperties(student, basicVO);
        basicVO.setSchoolName(tenant.getTenantName());
        basicVO.setStudentId(studentId);

        return basicVO;
    }

    @Override
    public LearningOverviewRespVO getLearningOverview(String studentId, Integer page, Integer size) {

        // 1. 验证学生是否存在
        UserEntity student = dataAggregationService.getStudentById(studentId);
        if (student == null) {
            throw new RuntimeException("学生不存在");
        }

        // 2. 获取学生的所有课程
        List<CourseStudentEntity> courseStudents = dataAggregationService.getStudentCourse(studentId);
        if (courseStudents == null || courseStudents.isEmpty()) {
            // 如果没有选课记录，返回空列表
            return buildEmptyResponse(studentId, student.getRealName(), page, size);
        }

        // 3. 构建课程绩效列表
        List<CoursePerformanceSimpleVO> coursePerformanceList = buildCoursePerformanceList(courseStudents);

        // 4. 按学年学期排序（最新的在前）
        sortCoursePerformanceByAcademicYear(coursePerformanceList);

        // 5. 分页处理
        List<CoursePerformanceSimpleVO> pagedList = applyPagination(coursePerformanceList, page, size);

        // 6. 构建分页信息
        PaginationVO pagination = buildPagination(coursePerformanceList.size(), page, size);

        // 7. 构建返回对象
        LearningOverviewRespVO response = new LearningOverviewRespVO();
        response.setStudentId(studentId);
        response.setRealName(student.getRealName());
        response.setCoursePerformance(pagedList);
        response.setPagination(pagination);

        return response;
    }

    /**
     * 构建课程绩效列表
     */
    private List<CoursePerformanceSimpleVO> buildCoursePerformanceList(List<CourseStudentEntity> courseStudents) {
        List<CoursePerformanceSimpleVO> result = new ArrayList<>();

        for (CourseStudentEntity courseStudent : courseStudents) {
            // 获取课程信息
            CourseEntity course = dataAggregationService.getCourseById(courseStudent.getCourseId());
            if (course == null) {
                continue; // 如果课程不存在，跳过
            }

            CoursePerformanceSimpleVO vo = new CoursePerformanceSimpleVO();
            vo.setCourseId(course.getCourseId());
            vo.setCourseName(course.getCourseName());

            // 设置总得分，处理可能的null值
            if (courseStudent.getScore() != null) {
                vo.setTotalScore(courseStudent.getScore().doubleValue());
            }

            // 设置课程排名
            vo.setClassRanking(courseStudent.getCourseRank());

            result.add(vo);
        }

        return result;
    }

    /**
     * 按学年学期排序（最新的在前）
     */
    private void sortCoursePerformanceByAcademicYear(List<CoursePerformanceSimpleVO> coursePerformanceList) {
        // 为了按学年排序，我们需要获取每个课程的学年信息
        Map<String, String> courseAcademicYearMap = new HashMap<>();

        for (CoursePerformanceSimpleVO vo : coursePerformanceList) {
            CourseEntity course = dataAggregationService.getCourseById(vo.getCourseId());
            if (course != null && course.getAcademicYear() != null) {
                courseAcademicYearMap.put(vo.getCourseId(), course.getAcademicYear());
            }
        }

        // 按学年降序排序
        coursePerformanceList.sort((o1, o2) -> {
            String year1 = courseAcademicYearMap.get(o1.getCourseId());
            String year2 = courseAcademicYearMap.get(o2.getCourseId());

            // 处理null值
            if (year1 == null && year2 == null) return 0;
            if (year1 == null) return 1;
            if (year2 == null) return -1;

            // 按学年字符串降序排列
            return year2.compareTo(year1);
        });
    }

    /**
     * 应用分页
     */
    private List<CoursePerformanceSimpleVO> applyPagination(List<CoursePerformanceSimpleVO> list, Integer page, Integer size) {
        int fromIndex = (page - 1) * size;
        if (fromIndex >= list.size()) {
            return new ArrayList<>();
        }

        int toIndex = Math.min(fromIndex + size, list.size());
        return list.subList(fromIndex, toIndex);
    }

    /**
     * 构建分页信息
     */
    private PaginationVO buildPagination(int total, Integer page, Integer size) {
        int totalPages = (int) Math.ceil((double) total / size);

        return PaginationVO.builder()
                .page(page)
                .size(size)
                .total(total)
                .totalPages(totalPages)
                .build();
    }

    /**
     * 构建空响应
     */
    private LearningOverviewRespVO buildEmptyResponse(String studentId, String realName, Integer page, Integer size) {
        LearningOverviewRespVO response = new LearningOverviewRespVO();
        response.setStudentId(studentId);
        response.setRealName(realName);
        response.setCoursePerformance(new ArrayList<>());
        response.setPagination(PaginationVO.builder()
                .page(page)
                .size(size)
                .total(0)
                .totalPages(0)
                .build());
        return response;
    }

    @Override
    public List<StudentCourseVO> getStudentCourses(String studentId) {

        // 1. 获取学生的选课关系列表
        List<CourseStudentEntity> courseStudents = dataAggregationService.getStudentCourse(studentId);

        // 2. 转换为VO列表
        return courseStudents.stream()
                .map(this::convertToStudentCourseVO)
                .collect(Collectors.toList());
    }

    /**
     * 将选课关系实体转换为课程VO
     */
    private StudentCourseVO convertToStudentCourseVO(CourseStudentEntity courseStudent) {
        StudentCourseVO vo = new StudentCourseVO();

        // 设置选课关系表中的基础信息
        vo.setCourseId(courseStudent.getCourseId());
        vo.setCourseRank(courseStudent.getCourseRank());
        vo.setScore(courseStudent.getScore());
        vo.setEnrollmentTime(courseStudent.getEnrollmentTime() != null ?
                courseStudent.getEnrollmentTime().toString() : null);

        // 获取课程详细信息
        CourseEntity course = dataAggregationService.getCourseById(courseStudent.getCourseId());
        if (course != null) {
            vo.setCourseName(course.getCourseName());
            vo.setAcademicYear(course.getAcademicYear());
            vo.setCourseIntro(course.getCourseIntro());
            vo.setStudentCount(course.getStudentCount());

            // 获取教师信息
            UserEntity teacher = dataAggregationService.getUserById(course.getTeacherId());
            if (teacher != null) {
                vo.setTeacherName(teacher.getRealName());
            }
        }

        return vo;
    }

    @Override
    public List<StudentTopSubmissionSimpleVO> getStudentTopSubmissionsSimple(String studentId) {
        try {
            return dataAggregationMapper.getTopSubmissionsSimple(studentId);
        } catch (Exception e) {
            throw new RuntimeException("获取核心成果失败", e);
        }
    }

    @Override
    public List<StudentTopSubmissionDetailVO> getStudentTopSubmissionsDetail(String studentId) {
        try {
            return dataAggregationMapper.getTopSubmissionsDetail(studentId);
        } catch (Exception e) {
            throw new RuntimeException("获取核心成果详情失败", e);
        }
    }

    @Override
    public SubmissionDetailVO getSubmissionDetailById(String submissionId) {
        try {
            return dataAggregationMapper.getSubmissionDetailById(submissionId);
        } catch (Exception e) {
            throw new RuntimeException("获取提交详情失败", e);
        }
    }

    @Override
    public CourseTopSubmissionVO getTopSubmissionByStudentAndCourse(String studentId, String courseId) {
        try {

            // 验证学生和课程是否存在
            UserEntity student = dataAggregationService.getStudentById(studentId);
            if (student == null) {
                throw new RuntimeException("学生不存在");
            }

            CourseEntity course = dataAggregationService.getCourseById(courseId);
            if (course == null) {
                throw new RuntimeException("课程不存在");
            }

            // 验证学生是否选修了该课程
            List<CourseStudentEntity> studentCourses = dataAggregationService.getStudentCourse(studentId);
            boolean isEnrolled = studentCourses.stream()
                    .anyMatch(cs -> cs.getCourseId().equals(courseId));

            if (!isEnrolled) {
                throw new RuntimeException("学生未选修该课程");
            }

            return dataAggregationMapper.getTopSubmissionByStudentAndCourse(studentId, courseId);

        } catch (Exception e) {
            throw new RuntimeException("获取最高得分提交失败: " + e.getMessage());
        }
    }
}